<template>


  <div class="ol-map" :id="id">
    <div id="mouse-position"></div>
    <form class="form print-form">
      <div>
        <v-layout>
          <!--<v-btn @click="searchPosition" color="info" id="search-position">查询坐标</v-btn>-->
          <!--<v-btn @click="test" color="info">获取地图点</v-btn>-->

          <v-btn @click="draw(drawType.point)" color="info" id="draw-point">点</v-btn>
          <v-btn @click="draw(drawType.line)" color="info" id="draw-line">线</v-btn>
          <v-btn @click="draw(drawType.polygon)" color="info" id="draw-ploygon">面</v-btn>
          <v-btn @click="draw(drawType.circle)" color="info" id="draw-circle">圆形</v-btn>
          <v-btn @click="draw(drawType.diamond)" color="info" id="draw-square">菱形</v-btn>
          <v-btn @click="draw(drawType.rec)" color="info" id="draw-box">矩形</v-btn>
          <!--<v-btn @click="reShape" color="info" id="reshape">修改形状</v-btn>-->
          <v-btn @click="exitDraw" color="info" id="exitDraw">结束绘制</v-btn>

          <!--<v-btn @click="printMap" color="info" id="print">打印地图</v-btn>-->

          <!--<v-btn @click="addShangHai" color="info" id="shanghai">标记上海</v-btn>-->
          <v-btn @click="showSatellite" color="info" id="tian_di_tu_satellite_layer">卫星图</v-btn>
          <v-btn @click="clean" color="info" id="clean">清空</v-btn>


          <v-text-field
            label="fx"
            placeholder="fx"
            v-model="filePoint.fx"
            :rules="rules.fxRule"

          ></v-text-field>


          <v-text-field
            label="fy"
            placeholder="fy"
            v-model="filePoint.fy"
            :rules="rules.fyRule"
          ></v-text-field>

          <v-btn @click="addFiledPoint" color="info" id="gs">增加点</v-btn>


          <v-text-field
            label="textLaber"
            placeholder="textLaber"
            v-model="textLaber.text"
          ></v-text-field>

          <v-btn @click="addTextLaber" color="info" id="textAdd">增加文字</v-btn>

        </v-layout>

      </div>


    </form>

    <!--<div id="css_animation"></div>-->
    <div style="display: none;">
      <a class="overlay" id="Shanghai" target="_blank" href="http://en.wikipedia.org/wiki/Shanghai">
        Shanghai
      </a>
      <div id="marker" title="Marker"></div>
      <div id="popup" title="点击查询:" class="ol-popup">
        <a href="#" id="popup-closer" class="ol-popup-closer"></a>
        <div id="popup-content"></div>
      </div>
    </div>
  </div>
</template>

<script>
  const ol = require('openlayers');
  require('openlayers/dist/ol.css');
  var jsPDF = require("jspdf");
  import {
    tian_di_tu_bgmap,
    tian_di_tu_annotation,
    tian_di_tu_satellite_layer, mousePositionControl,
  } from '../../mockDB';


  // zoom
  var zoom = {
    required: false,
    type: Number,
    default: 10
  };


  // 输出pdf用
  var dims = {
    a0: [1189, 841],
    a1: [841, 594],
    a2: [594, 420],
    a3: [420, 297],
    a4: [297, 210],
    a5: [210, 148]
  };

  // 卫星
  var isSatellite = true;


  // 绘图层
  var source = new ol.source.Vector({wrapX: false});
  var draw, select, modify;
  var drawVector = new ol.layer.Vector({
    source: source,
    style: new ol.style.Style({ //修改绘制的样式
      fill: new ol.style.Fill({
        color: 'rgba(255, 255, 255, 0.2)'
      }),
      stroke: new ol.style.Stroke({
        color: '#645fff',
        width: 2
      }),
      image: new ol.style.Circle({
        radius: 7,
        fill: new ol.style.Fill({
          color: '#ff002c'
        })
      })
    })
  });


  /***
   * 根据不同种类绘制图形
   * @param map ol.map
   * @param shapeName 图形名称
   */
  function drawFeatureWithName(map, shapeName) {
    map.removeLayer(drawVector);
    map.addLayer(drawVector);
    var geometryFunction, shapeName, maxPoints;
    map.removeInteraction(draw); //点击选择时候  取消绘图交互
    map.removeInteraction(select); //点击选择时候  取消选择
    map.removeInteraction(modify); //点击选择时候  取消修改

    switch (shapeName) {
      case "点":
        shapeName = 'Point';
        break;
      case "线":
        shapeName = 'LineString';
        break;
      case "面":
        shapeName = 'Polygon';
        break;
      case "圆形":
        shapeName = 'Circle';
        break;
      case "菱形":
        shapeName = 'Circle';
        geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
        break;
      case "矩形":
        shapeName = 'LineString';
        maxPoints = 2;
        geometryFunction = function (coordinates, geometry) {
          if (!geometry) {
            geometry = new ol.geom.Polygon(null);
          }
          var start = coordinates[0];
          var end = coordinates[1];
          geometry.setCoordinates([
            [start, [start[0], end[1]], end, [end[0], start[1]], start]
          ]);

          return geometry;
        };
        break;


    }

    draw = new ol.interaction.Draw({
      source: source,
      type: shapeName,
      geometryFunction: geometryFunction,
      maxPoints: maxPoints,
      // freehand: true // 是否随意会直线
    });

    // 绘图完成后做什么
    draw.addEventListener("drawend", function (evt) {
      var feature = evt.feature;
      // 坐标
      var geometry = feature.getGeometry();
      var coordinate = geometry.getCoordinates();
      alert("绘制完成");
      console.log(geometry);
      console.log(coordinate);
    });
    map.addInteraction(draw);
  }


  /**
   * bug 文字叠加了
   * @param feature
   * @param textName
   * @returns {ol.style.Style}
   */
  function createLabelStyle(feature, textName) {

    return new ol.style.Style({
      text: new ol.style.Text({
        textAlign: 'center',            //位置
        textBaseline: 'middle',         //基准线
        font: 'normal 14px 微软雅黑',    //文字样式
        text: textName,      //文本内容
        fill: new ol.style.Fill({       //文本填充样式（即文字颜色)
          color: '#000'
        }),
        stroke: new ol.style.Stroke({
          color: '#F00',
          width: 1
        })
      })
    });
  }


  export default {
    name: 'Map',
    props: {
      lat: {
        required: false,
        type: Number
      },
      lon: {
        required: false,
        type: Number
      },
      zoom: zoom
    },
    data() {
      return {
        map: {
          type: Object,
          default: {}
        }, filePoint: {
          fx: 120.01,
          fy: 30.01
        },
        textLaber: {
          text: ""
        },
        drawType: {
          point: "点",
          line: "线",
          polygon: "面",
          circle: "圆形",
          diamond: "菱形",
          rec: "矩形",
        },
        rules: {
          fxRule: [
            v => !!v || 'fx不能空',
            v => /[1-9]\d*\.\d*|0\.\d*[1-9]\d*/.test(v) || "fx浮点数"
          ], fyRule: [
            v => !!v || 'fy不能空',
            v => /[1-9]\d*\.\d*|0\.\d*[1-9]\d*/.test(v) || "fy浮点数"
          ]
        }

      }
    },
    computed: {
      id() {
        return this.$options.name + '-' + this._uid
      }
    }, methods: {


      addTextLaber: function () {
        var tt = this.textLaber.text;
        const x = eval(this.filePoint.fx);
        const y = eval(this.filePoint.fy);
        this.map.removeInteraction(draw);
        this.map.removeInteraction(select);
        this.map.removeInteraction(modify);

        var vectorSource = new ol.source.Vector({});
        var vectorLayer = new ol.layer.Vector({
          source: vectorSource
        });

        this.map.addLayer(vectorLayer);
        var aaaa = ol.proj.transform(
          [x, y], 'EPSG:4326', 'EPSG:3857');
        var newFeature = new ol.Feature({
          geometry: new ol.geom.Point(aaaa),
          name: tt
        });
        newFeature.setStyle(createLabelStyle(newFeature, tt));
        vectorSource.addFeature(newFeature);


        // this.map.on("click", function (evt) {
        //   var coordinate = evt.coordinate;
        //   var newFeature = new ol.Feature({
        //     geometry: new ol.geom.Point([13286666.44167076, 3545837.3051210414]),
        //     name: tt
        //   });
        //   newFeature.setStyle(createLabelStyle(newFeature, tt));
        //   vectorSource.addFeature(newFeature);
        // });

      },


      test: function () {

        var select = new ol.interaction.Select();
        this.map.addInteraction(select);
        var x, y;
        select.on('select', function (e) {
          const oneData = e.selected[0];
          x = oneData.getGeometry().getCoordinates()[0];
          y = oneData.getGeometry().getCoordinates()[0];
          const featureName = oneData.getProperties().name;
          console.log(x, y);
        });


        console.log();


      },

      draw: function (drawType) {
        const shapeName = drawType;
        drawFeatureWithName(this.map, shapeName);
        console.log("绘制" + drawType);
      },

      reShape: function () {
        this.map.removeInteraction(draw);
        this.map.removeInteraction(select);
        this.map.removeInteraction(modify);
        var select = new ol.interaction.Select({
          wrapX: false
        });
        var modify = new ol.interaction.Modify({
          features: select.getFeatures()
        });
        this.map.addInteraction(select);
        this.map.addInteraction(modify);
        console.log("修改图象");
      },

      exitDraw: function () {
        this.map.removeInteraction(draw);
        this.map.removeInteraction(select);
        this.map.removeInteraction(modify);
      },

      clean: function () {
        this.map.getOverlays().clear();
        this.map.getLayers().clear();
        this.map.addLayer(tian_di_tu_bgmap);
        this.map.addLayer(tian_di_tu_annotation);
        console.log("清空所有图");
      },

      printMap: function () {
        // 打印地图

        this.map.removeInteraction(draw); //点击选择时候  取消绘制
        var dims = {
          a0: [1189, 841],
          a1: [841, 594],
          a2: [594, 420],
          a3: [420, 297],
          a4: [297, 210],
          a5: [210, 148]
        };
        var loading = 0;
        var loaded = 0;
        document.body.style.cursor = 'progress';

        // 强制设置尺寸
        var format = 'a0';
        var dim = [210, 148];
        // 设置dpi
        var resolution = 150;
        var width = Math.round(dim[0] * resolution / 25.4);
        var height = Math.round(dim[1] * resolution / 25.4);
        var size = /** @type {ol.Size} */ (this.map.getSize());
        var extent = this.map.getView().calculateExtent(size);

        var source = tian_di_tu_bgmap.getSource();
        var tileLoadStart = function () {
          ++loading;
        };

        var tileLoadEnd = function () {
          ++loaded;
          if (loading === loaded) {
            var canvas = this;
            window.setTimeout(function () {
              loading = 0;
              loaded = 0;
              var data = canvas.toDataURL('image/png'); //canvas
              var pdf = new jsPDF('landscape', undefined, format);
              pdf.addImage(data, 'JPEG', 0, 0, dim[0], dim[1]);
              pdf.save('map.pdf');
              source.un('tileloadstart', tileLoadStart);
              source.un('tileloadend', tileLoadEnd, canvas);
              source.un('tileloaderror', tileLoadEnd, canvas);
              this.map.setSize(size);
              this.map.getView().fit(extent, size);
              this.map.renderSync();
              // exportButton.disabled = false;
              document.body.style.cursor = 'auto';
            }, 100);
          }
        };

        this.map.once('postcompose', function (event) {
          source.on('tileloadstart', tileLoadStart);
          source.on('tileloadend', tileLoadEnd, event.context.canvas);
          source.on('tileloaderror', tileLoadEnd, event.context.canvas);
        });

        this.map.setSize([width, height]);
        this.map.getView().fit(extent, /** @type {ol.Size} */(this.map.getSize()));
        this.map.renderSync();

      },


      addFiledPoint: function () {
        // ok 增加点
        const x = eval(this.filePoint.fx);
        const y = eval(this.filePoint.fy);
        const layer = new ol.layer.Vector({
          source: new ol.source.Vector({
            features: [new ol.Feature({
              geometry: new ol.geom.Point(ol.proj.transform([x, y], 'EPSG:4326', 'EPSG:3857')),
            })],
          }),

          style: new ol.style.Style({
            // image: new ol.style.Circle({
            //   radius: 15,
            //   fill: new ol.style.Fill({
            //     color: 'red'
            //   })
            // })
            image: new ol.style.Icon(({
              // 图片地址
              src: ''
            })),

          }),
          opacity: 0.5
        });

        this.map.addLayer(layer);
        const nowView = new ol.View(
          {
            center: ol.proj.fromLonLat([x, y]),
            zoom: 10
          });
        this.map.setView(nowView);

      },

      searchPosition() {
        // 点选坐标查询
        this.map.on("click", function (evt) {
          const coordinate = evt.coordinate;
          const hdms = ol.coordinate.toStringHDMS(ol.proj.transform(
            coordinate, 'EPSG:4326', 'EPSG:4326'));
          // 弹窗
          console.log("点选坐标" + hdms);
          alert(hdms);

        });


      },
      showSatellite() {
        // 显示天地图卫星
        var s = this.map.getLayers();
        console.log("当前有图册" + s.getLength());
        if (isSatellite) {
          s.clear();
          this.map.addLayer(tian_di_tu_satellite_layer);
          this.map.addLayer(tian_di_tu_annotation);
          isSatellite = false;
        } else {
          s.clear();
          this.map.addLayer(tian_di_tu_bgmap);
          this.map.addLayer(tian_di_tu_annotation);

          isSatellite = true
        }
      },
      addShangHai() {
        // 标记上海
        var pos = ol.proj.fromLonLat([120.0, 30.0]); //经纬度坐标转换
        var marker = new ol.Overlay({
          position: pos,
          positioning: 'center-center',
          element: document.getElementById('marker'),
          stopEvent: false
        });
        var Shanghai = new ol.Overlay({
          position: pos,
          element: document.getElementById('Shanghai'),
        });
        this.map.addOverlay(Shanghai);
        console.log("标记上海，坐标假的")
      }

    }
    ,
    mounted() {
      this.map = new ol.Map({
        target: this.id,
        // 图层
        layers: [
          tian_di_tu_bgmap, tian_di_tu_annotation,
        ],
        // 视图
        view: new ol.View(
          {
            center: ol.proj.fromLonLat([120, 30]),
            zoom: this.zoom

          }),
        // 控件
        controls: [
          new ol.control.FullScreen(), //全屏控件
          new ol.control.ScaleLine(), //比例尺
          mousePositionControl,
        ],
        // extent: []// 地图范围 传参数 minX minY maxX maxY
      });
    }
    ,
    created() {

    }


  }

</script>

<style scoped>

  .map:-moz-full-screen {
    height: 100%;
  }

  .map:-webkit-full-screen {
    height: 100%;
  }

  .map:-ms-fullscreen {
    height: 100%;
  }

  .map:fullscreen {
    height: 100%;
  }

  .ol-rotate {
    top: 3em;
  }

  #map {
    /*height: 550px;*/
    z-index: 999;
  }


  /*标记*/

  #marker {
    width: 20px;
    height: 20px;
    border: 1px solid #088;
    border-radius: 10px;
    background-color: #0FF;
    opacity: 0.5;
  }


  /*popup*/

  .ol-popup {
    position: absolute;
    background-color: white;
    -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
    filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
    padding: 15px;
    border-radius: 10px;
    border: 1px solid #cccccc;
    bottom: 12px;
    left: -50px;
    min-width: 280px;
  }

  .ol-popup:after,
  .ol-popup:before {
    top: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
  }

  .ol-popup:after {
    border-top-color: white;
    border-width: 10px;
    left: 48px;
    margin-left: -10px;
  }

  .ol-popup:before {
    border-top-color: #cccccc;
    border-width: 11px;
    left: 48px;
    margin-left: -11px;
  }

  .ol-popup-closer {
    text-decoration: none;
    position: absolute;
    top: 2px;
    right: 8px;
  }

  .ol-popup-closer:after {
    content: "✖";
  }

  #css_animation {
    height: 30px;
    width: 30px;
    border-radius: 25px;
    background: rgb(255, 0, 0);
    transform: scale(0.2);
    animation: myfirst 2s;
    animation-iteration-count: infinite;
    z-index: 200;
  }

  @keyframes myfirst {
    to {
      transform: scale(0.8);
      background: rgba(255, 0, 0, 0);
    }
  }
</style>
